<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Models\Article;
use App\Transformers\ArticleTransformer;
use Dingo\Api\Transformer\Factory;
use Illuminate\Support\Facades\DB;

class ArticleController extends Controller
{
    // 文章列表
    public function article_list(Request $request,Article $article,Factory $transformerfactory)
    {
        $transformerfactory->disableEagerLoading();
        $query = $article->query();
        if ($categoryId = $request->cid) {
            $query->where('cid', $categoryId);
        }

        if ($keyword = $request->keyword) {
            $query->where('title','like', $keyword.'%');
        }

        if ($order = $request->order) {
            $query->orderBy('click',$order);
        }

        # 选取字段
        $query->select('aid','title','created_at','updated_at','cid','author','keywords','click','comment_num','description');
        $articles = $query->paginate(10);
        return $this->response->paginator($articles, new ArticleTransformer());
    }

    // 文章详情
    public function article_detail(Article $article,$aid)
    {
        if(!preg_match('/^[1-9]\d*$/',$aid)) return $this->response->array(['err_code'=>101,'err_msg'=>'参数错误']);
        # 获取文章详情
        $article_detail = $article->query()->where('aid',$aid)->first();
        # 获取文章评论
        $comment_list = $article->getComments($aid);
        # 增加浏览量
        $res = DB::table('article')->where('aid',$aid)->increment('click');
        # 获取相关推荐
        $relation_article = DB::table('article')->where('cid',$article_detail->cid)->orderBy('aid','desc')->select('title','aid')->limit(8)->get();
        if($res){
            return $this->response->array(['atticle_detail'=>$article_detail,'relation_article'=>$relation_article,'comment_list'=>$comment_list]);
        } else {
            return $this->response->array(['err_code'=>101,'err_msg'=>'未查询到相关文章']);
        }
    }
}
